package com.ruoyi.energize.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.energize.domain.*;
import com.ruoyi.energize.util.GetGenderData;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.energize.service.IWdzAgeGenderDistributionService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 年龄性别精准客流Controller
 *
 * @author ruoyi
 * @date 2023-06-19
 */
@RestController
@RequestMapping("/energize/ageAndGenderDistribution")
@Component //使spring管理
//@EnableScheduling //定时任务注解
public class WdzAgeGenderDistributionController extends BaseController
{
    @Autowired
    private IWdzAgeGenderDistributionService wdzAgeGenderDistributionService;


    /**
     * 精准客流数据
     */
    @Scheduled(cron = "0 0 3 * * ?")
    //@GetMapping("/getSyncYesterdayAgeAndGenderData")
    public void getSyncYesterdayAgeAndGenderData(){
        System.out.println("每日上午3点执行一次同步精准客流信息脚本");
        Date day=new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
        SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String startHourTime = df.format(day);
        Date date = null;
        try {
            date = df.parse(startHourTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.DATE,-1);
        //cal.add(Calendar.DATE,-13);
        for (int i = 0; i < 24; i++) {
            cal.add(Calendar.HOUR, 1);
            date = cal.getTime();
            String endHourTime = format.format(date);
            //使用开始时间和结束时间统计精准客流数据
            //1、按照天同步客流量
            GetGenderData getGenderData=new GetGenderData();
            System.out.println(startHourTime+"=============="+endHourTime);
            String ageDistributionJsonStr=getGenderData.getSyncYesterdayAgeAndGenderData(startHourTime,endHourTime);
            startHourTime=endHourTime;//将结束的小时数，赋值给小时的开始数
            //解析json字符串
            this.stringToJsonobject(ageDistributionJsonStr,endHourTime);

        }

    }

    public void stringToJsonobject(String stringJson,String endHourTime){
        //System.out.println(stringJson+"*******************"+endHourTime);
        JSONObject jsonObject = (JSONObject) JSONObject.parse(stringJson);
        //获取 msg
        if(jsonObject.get("result").equals("请求数据成功!")){
            //获取ageDistribution数组数据
            JSONObject data=jsonObject.getJSONObject("data");
            JSONArray ageDistributionList= data.getJSONArray("ageDistribution");
            List<WdzAgeDistributionVo> WdzAgeDistributionVoList=new ArrayList<>();
            WdzAgeDistributionVoList=ageDistributionList.toJavaList(WdzAgeDistributionVo.class);
            List<WdzGenderDistributionVo> wdzGenderDistributionVoList=new ArrayList<>();
            if(WdzAgeDistributionVoList.size()>0){
                WdzAgeGenderDistribution wdzAgeGenderDistribution=new WdzAgeGenderDistribution();
                for (WdzAgeDistributionVo wdzAgeDistributionVo:WdzAgeDistributionVoList){
                    //分析精准客流数据，整理好后插入到精准客流数据表中
                    wdzGenderDistributionVoList=wdzAgeDistributionVo.getGenderDistribution();
                    if (wdzGenderDistributionVoList.size()>0) {//说明查询到相关数据
                        //使用list批量插入到万店掌门店列表中去
                        for (WdzGenderDistributionVo wdzGenderDistributionVo:wdzGenderDistributionVoList){
                            if(wdzAgeDistributionVo.getAgeDivisionType().equals(0)){//儿童
                                if(wdzGenderDistributionVo.getGender().equals(1)){//男性
                                    wdzAgeGenderDistribution.setChildMaleNum(wdzGenderDistributionVo.getPeopleNum());
                                }else if(wdzGenderDistributionVo.getGender().equals(2)){//女性
                                    wdzAgeGenderDistribution.setChildFemaleNum(wdzGenderDistributionVo.getPeopleNum());
                                }else if(wdzGenderDistributionVo.getGender().equals(0)){//未知
                                    wdzAgeGenderDistribution.setChildUnknownNum(wdzGenderDistributionVo.getPeopleNum());
                                }
                            }else if(wdzAgeDistributionVo.getAgeDivisionType().equals(1)){//中年人
                                if(wdzGenderDistributionVo.getGender().equals(1)){//男性
                                    wdzAgeGenderDistribution.setWrinklyMaleNum(wdzGenderDistributionVo.getPeopleNum());
                                }else if(wdzGenderDistributionVo.getGender().equals(2)){//女性
                                    wdzAgeGenderDistribution.setWrinklyFemaleNum(wdzGenderDistributionVo.getPeopleNum());
                                }else if(wdzGenderDistributionVo.getGender().equals(0)){//未知
                                    wdzAgeGenderDistribution.setWrinklyUnknownNum(wdzGenderDistributionVo.getPeopleNum());
                                }
                            }else if(wdzAgeDistributionVo.getAgeDivisionType().equals(2)){//老年人
                                if(wdzGenderDistributionVo.getGender().equals(1)){//男性
                                    wdzAgeGenderDistribution.setAgedMaleNum(wdzGenderDistributionVo.getPeopleNum());
                                }else if(wdzGenderDistributionVo.getGender().equals(2)){//女性
                                    wdzAgeGenderDistribution.setAgedFemaleNum(wdzGenderDistributionVo.getPeopleNum());
                                }else if(wdzGenderDistributionVo.getGender().equals(0)){//未知
                                    wdzAgeGenderDistribution.setAgedUnknownNum(wdzGenderDistributionVo.getPeopleNum());
                                }
                            }
                        }
                    }
                }
                //将时间戳转化成date类型
                wdzAgeGenderDistribution.setCreateTime(this.stringToDate(endHourTime));
                wdzAgeGenderDistributionService.insertWdzAgeGenderDistribution(wdzAgeGenderDistribution);
            }
            //休眠1s继续执行循环
            try {
                Thread.sleep(1000L);//单位：毫秒
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }

    //时间戳由string转date类型
    public Date stringToDate(String timeString){
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = null;
        try {
            date = df.parse(timeString);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    /**
     * 查询年龄性别精准客流列表
    */
    @PreAuthorize("@ss.hasPermi('energize:ageAndGenderDistribution:list')")
    @GetMapping("/list")
    public TableDataInfo list(WdzAgeGenderDistribution wdzAgeGenderDistribution)
    {
        startPage();
        List<WdzAgeGenderDistribution> list = wdzAgeGenderDistributionService.selectWdzAgeGenderDistributionList(wdzAgeGenderDistribution);
        return getDataTable(list);
    }

    /**
     * 导出年龄性别精准客流列表
     */
    @PreAuthorize("@ss.hasPermi('energize:ageAndGenderDistribution:export')")
    @Log(title = "年龄性别精准客流", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, WdzAgeGenderDistribution wdzAgeGenderDistribution)
    {
        List<WdzAgeGenderDistribution> list = wdzAgeGenderDistributionService.selectWdzAgeGenderDistributionList(wdzAgeGenderDistribution);
        ExcelUtil<WdzAgeGenderDistribution> util = new ExcelUtil<WdzAgeGenderDistribution>(WdzAgeGenderDistribution.class);
        util.exportExcel(response, list, "年龄性别精准客流数据");
    }

    /**
     * 获取年龄性别精准客流详细信息
     */
    @PreAuthorize("@ss.hasPermi('energize:ageAndGenderDistribution:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(wdzAgeGenderDistributionService.selectWdzAgeGenderDistributionById(id));
    }

    /**
     * 新增年龄性别精准客流
     */
    @PreAuthorize("@ss.hasPermi('energize:ageAndGenderDistribution:add')")
    @Log(title = "年龄性别精准客流", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody WdzAgeGenderDistribution wdzAgeGenderDistribution)
    {
        return toAjax(wdzAgeGenderDistributionService.insertWdzAgeGenderDistribution(wdzAgeGenderDistribution));
    }

    /**
     * 修改年龄性别精准客流
     */
    @PreAuthorize("@ss.hasPermi('energize:ageAndGenderDistribution:edit')")
    @Log(title = "年龄性别精准客流", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody WdzAgeGenderDistribution wdzAgeGenderDistribution)
    {
        return toAjax(wdzAgeGenderDistributionService.updateWdzAgeGenderDistribution(wdzAgeGenderDistribution));
    }

    /**
     * 删除年龄性别精准客流
     */
    @PreAuthorize("@ss.hasPermi('energize:ageAndGenderDistribution:remove')")
    @Log(title = "年龄性别精准客流", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(wdzAgeGenderDistributionService.deleteWdzAgeGenderDistributionByIds(ids));
    }
}
